package sort;

import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class BubbleSort {

    public static void bubbleSort(int[] arr){
        if(arr == null || arr.length <= 1){
            return;
        }

        int count = 0;

        int n = arr.length;
        for(int i = 1; i<n; i++){   // 一共做 n-1 趟
            for(int j=0; j<n-i; j++){   // 每一趟比较
                count++;
                if(arr[j] > arr[j+1]){
                    swap(arr, j, j+1);
                }
            }
        }
        System.out.println("比较次数：" + count);
    }

    public static void bubbleSortEnhance(int[] arr) {
        if(arr == null || arr.length <= 1){
            return;
        }

        int count = 0;

        int n = arr.length;
        boolean isChanged = false;
        for(int i = 1; i<n; i++){   // 一共做 n-1 趟
            isChanged = false;
            for(int j=0; j<n-i; j++){   // 每一趟比较
                count++;
                if(arr[j] > arr[j+1]){
                    swap(arr, j, j+1);
                    isChanged = true;
                }
            }

            if(isChanged == false){
                break;
            }
        }
        System.out.println("比较次数：" + count);
    }

    public static void swap(int[] arr, int i, int j){
        if( i == j){
            return;
        }
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        return;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62};
//        bubbleSort(arr);
        bubbleSortEnhance(arr);
        System.out.println(Arrays.stream(arr).boxed().collect(Collectors.toList()));

        int[] arrSorted = new int[]{1, 17, 21, 22, 29, 34, 50, 60, 61, 62, 72};
//        bubbleSort(arrSorted);
        bubbleSortEnhance(arrSorted);
        System.out.println(Arrays.stream(arrSorted).boxed().collect(Collectors.toList()));
    }
}
